<?php

/************************************************ 
 | Copyright Reserved © Oversea.com.au
 | Developper: Cavin Zhang
 | Date: Jan 7,2012
 | Program: For event&error logging&tracing
 */
class errorEventLog {
	
	public static $errLogPriority = array('DB_CONN'=>'CRITICAL','SQL_ERR'=>'HIGH','OPER_EXCEP'=>'MIDDLE','EXEC_UPDATE'=>'HIGH');
	private static $sysLogRootPath = '../debugLog/sys-basic-trace.log';
	private static $devLogTraceUsage = '../debugLog/php_sql_trace.log';
	private static $backupDirectory = '../debugLog/backup/bg_';
	private static $logFileLimitSize = 5242880; //5M 5242880
	private static $cronJobHistory = '../debugLog/cronjoblogs.log';
	
	public function __construct() {
		
	//TODO - Insert your code here
	}
	
	public static function errLogToFile($type,$msg)
	{
		global $webAddress;
		$bundleMsg = date("[Y-m-d H:i:s] ").'['.errorEventLog::$errLogPriority[$type].'] ['.$_SESSION[''].']*** '.self::getRequestURI().' *** '.$msg." \r\n"; 
		/* **************************************************
		 | The logs managed principle:
		 | If the origin one size over 30M ,then copy
		 | to the backup folder therefore recreate a new one
		 */
		if(file_exists(errorEventLog::$sysLogRootPath))
		{
			//check the currently using log file's size
			if(filesize(errorEventLog::$sysLogRootPath) >= errorEventLog::$logFileLimitSize)
			{
				$destDirectory = errorEventLog::$backupDirectory.date('Ymd').'_sys.bak';
				$moved = copy(errorEventLog::$sysLogRootPath,$destDirectory);
				if($moved)
				{
					//delete the old one as it is out of limit
					$del = @unlink(errorEventLog::$sysLogRootPath);	
				}
			}
			//clear the cache of the file object ,otherwise the filesize will be stored permanently 
			clearstatcache();
		}
		//To write in
		error_log($bundleMsg,'3',errorEventLog::$sysLogRootPath);
		if($type == 'DB_CONN')
		{
			/*
			 * If a critical disaster within the problem comes out, then interrupt the procedure immediately
			 */
			echo "<div style='text-align:center;padding-top:50px;'>
					<h1>抱歉，程序发生严重错误现已终止!请稍候再试...</h1></br>
					<h1>Sorry, there is critical error came out!Please try later..</h1>
				</div>";
			exit;
		}
	}
	
	/*****************************************************
	 | Function:
	 | To get the file name which encounters the problem
	 */
	protected static function getRequestURI()
	{
		if (isset($_SERVER['REQUEST_URI']))
	    {
	        $uri = $_SERVER['REQUEST_URI'];
	    }
	    else
	    {
	        if (isset($_SERVER['argv']))
	        {
	            $uri = $_SERVER['PHP_SELF'] .'?'. $_SERVER['argv'][0];
	        }
	        else
	        {
	            $uri = $_SERVER['PHP_SELF'] .'?'. $_SERVER['QUERY_STRING'];
	        }
	    }
	    return $uri;
	}
	
	public static function displaysSQLPhase($msg)
	{
		global $isDevelopmentMode;
		if ($isDevelopmentMode == 'ON')
		{
			if(filesize(errorEventLog::$devLogTraceUsage) >= errorEventLog::$logFileLimitSize)
			{
				$destDirectory = errorEventLog::$backupDirectory.date('Ymd').'_sql.bak';
				$moved = copy(errorEventLog::$devLogTraceUsage,$destDirectory);
				if($moved)
				{
					//delete the old one as it is out of limit
					$del = @unlink(errorEventLog::$devLogTraceUsage);	
				}
			}
			//clear the cache of the file object ,otherwise the filesize will be stored permanently 
			clearstatcache();
			//only development uses such logging ,for securing pupose
			$bundleMsg = date("[Y-m-d H:i:s] ").'[ Error SQL ]*** '.self::getRequestURI().' *** '.$msg." \r\n"; 
			$fp=fopen(errorEventLog::$devLogTraceUsage,'a');
			@fwrite($fp,$bundleMsg);
			@fclose($fp);
		}
	}
	/**
	 * 
	 * @param unknown_type $msg
	 * @param unknown_type $property  'S'tart,'E'nd,'P'rocess,'ER'ror,'EX'ception
	 */
	public static function autoEventRecorder($msg,$property = 'P')
	{
		if(filesize(errorEventLog::$cronJobHistory) >= errorEventLog::$logFileLimitSize)
		{
			$destDirectory = errorEventLog::$backupDirectory.date('Ymd').'_cronjoblogs.bak';
			$moved = copy(errorEventLog::$cronJobHistory,$destDirectory);
			if($moved)
			{
				//delete the old one as it is out of limit
				$del = @unlink(errorEventLog::$cronJobHistory);	
			}
		}
		clearstatcache();
		switch ($property){
			case 'S':
				$bundleMsg = date("[Y-m-d H:i:s] ").'[ CRON JOB Starts ]*** '.self::getRequestURI().' *** '.$msg." \r\n"; 
			break;
			case 'P':
				$bundleMsg = date("[Y-m-d H:i:s] ").'[ PROCESS RUNNING ]****** '.$msg." \r\n";
			break;
			case 'ER':
				$bundleMsg = date("[Y-m-d H:i:s] ").'[ !!ERROR!! ]****** '.$msg." \r\n"; 
			break;
			case 'E':
				$bundleMsg = date("[Y-m-d H:i:s] ").'[ CRON JOB End ]*** '.self::getRequestURI().' *** '.$msg." \r\n"; 
			break;
			case 'EX':
				$bundleMsg = date("[Y-m-d H:i:s] ").'[ EXCEPTION ]*** '.self::getRequestURI().' *** '.$msg." \r\n"; 
			break;
			default:
				return false;
		}
		$fp=fopen(errorEventLog::$cronJobHistory,'a');
			@fwrite($fp,$bundleMsg);
			@fclose($fp);
		
	}
}

?>